package org.example.backend.demos.web.Util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.example.backend.demos.web.result.ResultCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret:mySecretKeyForJWTTokenGenerationInNationalUnityProject2024}")
    private String secretKey;

    @Value("${jwt.expiration:86400000}")
    private long expiration;

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secretKey.getBytes());
    }

    /**
     * 生成token
     */
    public String generateToken(Long userId, String username, String role) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("role", role);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 从token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("userId", Long.class);
    }

    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }

    /**
     * 从token中获取用户角色
     */
    public String getRoleFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get("role", String.class);
    }

    /**
     * 验证token
     */
    public boolean validateToken(String token) {
        return !getClaimsFromToken(token).isEmpty();
    }

    /**
     * 验证管理员角色
     */
    public boolean isAdmin(String token) {
        try {
            String role = getRoleFromToken(token);
            return "admin".equals(role);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取Claims
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * token是否过期
     */
    public ResultCode isToken(String token) {
        try {
            getClaimsFromToken(token);
            return ResultCode.VALID_TOKEN;
        } catch (ExpiredJwtException e) {
            return ResultCode.EXPIRED_TOKEN;
        } catch (JwtException e) {
            return ResultCode.INVALID_TOKEN;
        }
    }


//    /**
//     * 生成测试token
//     */
//    public String generateTestToken() {
//        return generateToken(1001L, "testuser", "user");
//    }
//
//    /**
//     * 生成测试管理员token
//     */
//    public String generateTestAdminToken() {
//        return generateToken(1L, "admin", "admin");
//    }
}